import React, { Component } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { uploadUrl } from '@/config/index'
import {
  Card,
  Tabs,
  Button,
  Table,
  Select,
  Modal,
  Form,
  Input,
  Icon,
  Upload,
  Popconfirm,
  Divider,
  Radio,
  Badge
} from 'antd'
import { connect } from 'dva'
import { LZFormItem } from '@/components/LZForm'
import { getToken } from '@/utils/localStorage'
import commonApi from '@/services/common'
import MyConfigService from './services'

const { TabPane } = Tabs
const { Option } = Select

@connect()
@Form.create()
class MyConfigure extends Component {
  state = {
    visible: false, // modal的控制
    title: '', // modal的标题
    imgSrc: '',
    fileList: [],
    tabActiveKey: '1',
    pageNumber: 1,
    pageSize: 10,
    currentInfo: [], // 当前tab的信息
    loading: true,
    confirmLoading: false,
    channelData: [],
    tableData: []
  }

  componentDidMount() {
    this.getData()
    this.getChannel()
  }

  getColumns = () => {
    const { tabActiveKey } = this.state
    const { tabName } = this.tabMap[tabActiveKey]
    return [
      {
        title: 'ID',
        dataIndex: 'id',
        align: 'center',
        key: 'id'
      },
      {
        title: () => `${tabName}名称`,
        dataIndex: this.tabMap[tabActiveKey].name,
        align: 'center'
      },
      {
        title: () => `${tabName}图片`,
        dataIndex: 'imgSrc',
        align: 'center',
        render: text => <img src={text} className="table-cell-img" alt="" />
      },
      {
        title: '跳转链接',
        dataIndex: 'jumpUrl',
        align: 'center',
        key: 'jumpUrl',
        width: 200
      },
      {
        title: '上架渠道',
        dataIndex: 'channelName',
        align: 'center',
        width: 120,
        render: (text, record) => {
          return text && text.split('&').join(',')
        }
      },
      {
        title: '上线时间',
        dataIndex: 'createTime',
        align: 'center',
        key: 'createTime'
      },

      {
        title: '状态',
        dataIndex: 'status',
        align: 'center',
        key: 'status',
        render: text => {
          const success = text
          const status = success ? 'success' : 'default'
          const badgeText = success ? '有效' : '失效'
          return <Badge status={status} text={badgeText} />
        }
      },
      {
        title: '排序',
        dataIndex: 'indexSort',
        align: 'center',
        key: 'indexSort'
      },
      {
        title: '操作',
        align: 'center',
        key: 'action',
        render: (text, record) => (
          <div className="table-action">
            <a onClick={() => this.edit(record)}>修改</a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定要删除吗？"
              onConfirm={() => this.deleteItem(record)}
            >
              <a>删除</a>
            </Popconfirm>
          </div>
        )
      }
    ]
  }

  getData = () => {
    const { pageNumber, pageSize, tabActiveKey } = this.state
    const { getData } = this.tabMap[tabActiveKey]
    this.setState({
      loading: true
    })
    MyConfigService[getData]({
      pageNumber,
      pageSize
    })
      .then(res => {
        this.setState({
          tableData: res.records || [],
          total: res.total,
          current: res.current
        })
      })
      .finally(() => {
        this.setState({
          loading: false
        })
      })
  }

  // 通过这个map对不同的tab做不同的接口处理和数据展示
  tabMap = {
    '1': {
      name: 'serviceName',
      getData: 'queryOpeMyServicePage',
      delete: 'deleteOpeMyService',
      requestName: 'Service',
      tabName: '服务位',
      size: '202px*100px'
    },
    '2': {
      name: 'orderName',
      getData: 'queryOpeMyOrderPage',
      delete: 'deleteMyOrder',
      requestName: 'Order',
      tabName: '订单状态',
      size: '52px*46px'
    },
    '3': {
      name: 'toolName',
      getData: 'queryOpeMyToolPage',
      delete: 'deleteMyTool',
      requestName: 'Tool',
      tabName: '工具位',
      size: '60px*60px'
    }
  }

  deleteItem = record => {
    const { tabActiveKey } = this.state
    this.setState({
      loading: true
    })
    MyConfigService[this.tabMap[tabActiveKey].delete]({
      id: record.id
    })
      .then(res => {
        this.getData()
      })
      .finally(() => {
        this.setState({
          loading: false
        })
      })
  }

  // 获取上架渠道
  getChannel = () => {
    commonApi.selectPlateformChannel().then(res => {
      this.setState({
        channelData: res
      })
    })
  }

  // 页签的跳转
  onTabChange = key => {
    this.setState(
      {
        tabActiveKey: key,
        pageSize: 10,
        pageNumber: 1,
        loading: true
      },
      () => this.getData()
    )
  }

  // 新增
  add = () => {
    this.setState({
      visible: true,
      title: '新增',
      currentInfo: {},
      fileList: []
    })
  }

  edit = record => {
    const fileList = record.imgSrc
      ? [{ uid: record.id, url: record.imgSrc }]
      : []
    this.setState({
      visible: true,
      title: '修改tab',
      currentInfo: record,
      fileList,
      imgSrc: record.imgSrc
    })
  }

  // modal的确认
  handleOk = () => {
    this.props.form.validateFields((err, value) => {
      if (!err) {
        this.setState({
          confirmLoading: true
        })
        const { tabActiveKey, imgSrc, currentInfo, title } = this.state
        const { requestName } = this.tabMap[tabActiveKey]
        const action = title === '新增' ? 'add' : 'modify'
        MyConfigService[`${action}OpeMy${requestName}`]({
          ...value,
          channel: value.channel.join('&'),
          imgSrc: imgSrc || currentInfo.imgSrc,
          id: currentInfo.id
        })
          .then(res => {
            this.setState(
              {
                visible: false,
                confirmLoading: false,
                imgSrc: '',
                currentInfo: {},
                fileList: []
              },
              () => {
                this.props.form.resetFields()
                this.getData()
              }
            )
          })
          .finally(() => {
            this.setState({
              confirmLoading: false
            })
          })
      }
    })
  }

  // 上传的回调
  handleUploadChange = ({ file, fileList, event }) => {
    const filelist = [...fileList] || []
    if (file.status === 'done') {
      filelist.map(item => {
        this.setState({
          imgSrc: item.response.data
        })
      })
    }
    this.setState({
      fileList
    })
  }

  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }

  // 上传后下载的回调
  onDownload = file => {
    return window.open(this.state.imgSrc)
  }

  // 上传后删除的回调
  onRemove = () => {
    const { currentInfo } = this.state
    this.setState({
      fileList: [],
      imgSrc: '',
      currentInfo: { ...currentInfo, imgSrc: '' }
    })
  }

  // 分页，下一页
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber
      },
      () => {
        this.getData()
      }
    )
  }

  showTotal = () => {
    return `共有${this.state.total}条`
  }

  // 切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize,
        pageNumber: 1
      },
      () => {
        this.getData()
      }
    )
  }

  render() {
    const {
      loading,
      visible,
      confirmLoading,
      title,
      imgSrc,
      fileList,
      tabActiveKey,
      current,
      total,
      currentInfo,
      channelData,
      tableData
    } = this.state
    const tabs = [
      { name: '服务', id: 1 },
      { name: '我的订单', id: 2 },
      { name: '工具', id: 3 }
    ]
    const { indexSort, jumpUrl, status = true, channel } = currentInfo
    const channelIds = (channel && channel.split('&')) || []
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传照片</div>
      </div>
    )
    const currentTab = this.tabMap[tabActiveKey]
    return (
      <PageHeaderWrapper
        title={false}
        className="nav-tab"
        content={
          <div>
            <Button
              type="primary"
              className="w-112 single-btn"
              onClick={this.add}
            >
              新增
            </Button>
            <Tabs size="small" onChange={this.onTabChange}>
              {tabs.map(item => {
                return <TabPane tab={item.name} key={item.id} />
              })}
            </Tabs>
          </div>
        }
      >
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Table
            loading={loading}
            columns={this.getColumns()}
            dataSource={tableData}
            rowKey={record => record.id}
            pagination={{
              current,
              total,
              onChange: this.onChange,
              showTotal: this.showTotal,
              showQuickJumper: true,
              pageSizeOptions: ['3', '5', '10'],
              showSizeChanger: true,
              onShowSizeChange: this.onShowSizeChange
            }}
          />
        </Card>
        {/* 新增 */}
        <Modal
          title={title}
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          destroyOnClose
          onCancel={() => {
            this.setState({
              visible: false,
              currentInfo: {},
              fileList: [],
              imgSrc: ''
            })
          }}
        >
          <Form {...formItemLayout}>
            <Form.Item label="目标位置">
              {getFieldDecorator('address', {
                initialValue: tabActiveKey
              })(
                <Select disabled>
                  <Option value="1">服务</Option>
                  <Option value="2">我的订单</Option>
                  <Option value="3">工具</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item label={`${currentTab.tabName}名称`}>
              {getFieldDecorator(currentTab.name, {
                rules: [
                  {
                    required: true,
                    message: `${currentTab.tabName}名称不能为空`
                  }
                ],
                initialValue: currentInfo[currentTab.name]
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="跳转地址">
              {getFieldDecorator('jumpUrl', {
                rules: [
                  {
                    required: true,
                    message: '跳转地址不能为空'
                  }
                ],
                initialValue: jumpUrl
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="排序规则">
              {getFieldDecorator('indexSort', {
                rules: [
                  {
                    required: true,
                    message: '排序不能为空'
                  }
                ],
                initialValue: indexSort
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <LZFormItem
              label="状态"
              field="status"
              required
              getFieldDecorator={getFieldDecorator}
              initialValue={status}
            >
              <Radio.Group>
                <Radio value>有效</Radio>
                <Radio value={false}>无效</Radio>
              </Radio.Group>
            </LZFormItem>
            <Form.Item label="宣传图片">
              {getFieldDecorator('imgSrc', {
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      if (!value && imgSrc) {
                        callback('图片不能为空')
                      }
                      callback()
                    }
                  }
                ],
                initialValue: imgSrc || currentInfo.imgSrc
              })(
                <div className="upload-desc flex-column">
                  <Upload
                    accept="image/*"
                    action={uploadUrl}
                    listType="picture-card"
                    fileList={fileList}
                    headers={{
                      token: getToken()
                    }}
                    onPreview={this.handlePreview} // 预览
                    onRemove={this.onRemove} // 删除
                    onDownload={this.onDownload}
                    onChange={this.handleUploadChange}
                  >
                    {fileList.length >= 1 ? null : uploadButton}
                  </Upload>
                  <div className="size-desc">建议尺寸：{currentTab.size}</div>
                </div>
              )}
            </Form.Item>

            <Form.Item label="上架渠道">
              {getFieldDecorator('channel', {
                rules: [
                  {
                    required: true,
                    message: '上架渠道不能为空'
                  }
                ],
                initialValue: channelIds || []
              })(
                <Select
                  mode="multiple"
                  style={{ width: '100%' }}
                  placeholder="全部"
                >
                  {channelData.map((item, sign) => {
                    return (
                      <Option key={item.appId} value={item.channelId}>
                        {' '}
                        {item.channelName}{' '}
                      </Option>
                    )
                  })}
                </Select>
              )}
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title="图片预览"
          visible={this.state.imgVisible}
          footer={null}
          onCancel={() => this.setState({ imgVisible: false })}
        >
          <img
            alt="example"
            style={{ width: '100%' }}
            src={imgSrc || currentInfo.imgSrc}
          />
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default MyConfigure
